
import 'package:flutter/material.dart';
import 'package:local_auth/local_auth.dart';
import 'package:xim/config/config.dart';
import 'package:xim/http/store.dart';
import 'package:xim/widget/common/state.dart';
import 'package:xim/widget/common/ui/cell.dart';
import 'package:xim/widget/common/ui/sheet.dart';

class LoginSetting extends StatefulWidget {

  const LoginSetting({Key? key}) : super(key: key);

  @override
  State<LoginSetting> createState() => _LoginSettingState();
}

class _LoginSettingState extends AppBarState<LoginSetting> with AsyncState<LoginSetting>{
  /// 指纹
  bool enableFingerprint = false;
  /// 面部
  bool enableFace = false;
  /// 手势
  bool enableGesture = false;
  /// 默认本地身份认证方式
  var localIdentityVerifyType = LocalIdentityVerifyType.none;
  /// 支持的校验方式
  Set<LocalIdentityVerifyType> enableIdentityVerifyType = {};

  EdgeInsets cellPadding = const EdgeInsets.symmetric(vertical: 14,horizontal: 12);

  Color cellColor = Colors.white;
  Widget arrow = Cell.iconItem(iconData: Icons.chevron_right, iconStyle: IconStyle(size: 20));

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: appBar,
      body: Container(
        color: const Color(0xfff0eff4),
        child: Column(
          children: [
            Container(
              padding: cellPadding,
              color: cellColor,
              child: Column(
                children: [
                  Cell.titleCell(title: "刷脸登录", rightItem:
                    rightItem(enableIdentityVerifyType.contains(LocalIdentityVerifyType.face)?"支持":"不支持"),
                  ),
                  const Divider(),
                  Cell.titleCell(title: "指纹登录", rightItem:
                    rightItem(enableIdentityVerifyType.contains(LocalIdentityVerifyType.fingerprint)?"支持":"不支持"),
                  ),
                  const Divider(),
                  Cell.titleCell(title: "手势登录", rightItem:
                    rightItem(enableIdentityVerifyType.contains(LocalIdentityVerifyType.gesture)?"支持":"不支持"),
                  ),
                ],
              )
            ),
            const SizedBox(height: 20),
            Container(
              padding: cellPadding,
              color: cellColor,
              child: Cell.titleCell(
                title: "默认登录方式",
                rightItem: rightItem(localValidTypeName(localIdentityVerifyType)),
                onTab: (){
                  selectedBottomSheet(
                      context,
                      showCancelItem: true,
                      gap: 24,
                      itemFilter: (e)=>e.isNotEmpty,
                      enableIdentityVerifyType,
                      getItem: (it)=>localValidTypeName(it),
                      selectedCallBack: (selectedItem) async {
                        await storeLocalIdentityVerifyType(selectedItem);
                        setState(() {
                          localIdentityVerifyType = selectedItem;
                        });
                        if (context.mounted) Navigator.pop(context);
                      },
                  );
                },
              ),
            ),
          ],
        ),
      ),
    );
  }
  // TODO [local_auth#107210] 没法指定面部还是指纹识别
  String localValidTypeName(LocalIdentityVerifyType type){
    switch(type) {
      case LocalIdentityVerifyType.face:
        return "面部识别";
      case LocalIdentityVerifyType.gesture:
        return "图案手势";
      case LocalIdentityVerifyType.fingerprint:
        return "指纹识别";
      default:
        return "";
    }
  }

  Widget rightItem(String? text, {bool isShowArrow=true}){
    return Row(
    children: [
        if(text!=null) Text(text, style: const TextStyle(color: Colors.grey, fontSize: 14),),
        const SizedBox(width: 6,),
        if(isShowArrow) arrow,
      ],
    );
  }

  @override
  String get appBarTitle => "登录设置";

  @override
  Future<void> asyncInitState() async {

    var isEnableFingerprint = await takeAsBool(StoreKey.isEnableFingerprintLogin) ?? false;
    var isEnableFace= await takeAsBool(StoreKey.isEnableFaceLogin) ?? false;
    var isEnableGestureLogin = await takeAsBool(StoreKey.isEnableGestureLogin) ?? false;
    var localIdentityVerifyTypeCode = await takeLocalIdentityVerifyType();
    var auth = LocalAuthentication();
    /// 获取设备已注册的生物特征列表
    List<BiometricType> availableBiometrics = await auth.getAvailableBiometrics();
    for (var type in availableBiometrics) {
      switch (type) {
        case BiometricType.face:
        case BiometricType.strong:
          enableIdentityVerifyType.add(LocalIdentityVerifyType.face);
          break;
        case BiometricType.fingerprint:
        case BiometricType.weak:
          enableIdentityVerifyType.add(LocalIdentityVerifyType.fingerprint);
          break;
        default:
      }
    }
    setState(() {
      enableFingerprint = isEnableFingerprint;
      enableFace = isEnableFace;
      enableGesture = isEnableGestureLogin;
      localIdentityVerifyType = localIdentityVerifyTypeCode;
    });
  }

  @override
  Color get appBarBgColor => Colors.red;

}
